//获取应用实例
var app = getApp();
var FormCheckRule = {
    idCardRule1: /^[0-9]{14}([0-9]|X|x)$/,
    idCardRule2: /^[0-9]{17}([0-9]|X|x)$/,
    nameRule: /^[\u4e00-\u9fa5]{2,12}$/,
    telRule:/^[1]{1}[0-9]{10}$/,

    cardNbrNullMessage:"请输入身份证号！",
    cardNbrErrorMessage:"请输入正确的身份证号！",

    cardNameNullMessage:"请输入驾驶人姓名！",
    cardNameErrorMessage:"请输入正确的驾驶人姓名！",
    certPlaceNameNullMessage:"请选择考试城市！",
    certPlaceNameErrorMessage:"请选择正确的考试城市！",


    cellNumNullMessage:"请输入收件人电话！",
    cellNumErrorMessage:"请输入正确的收件人电话！",
    contactNameNullMessage:"请输入收件人姓名！",
    contactNameErrorMessage:"请输入正确的收件人姓名！",
    areaNameNullMessage:"请选择所在地区！",
    streetNullMessage:"请输入详细地址！",
    num:0

};


Page({
    data: {
        area:"请选择所在地区",
        certPlaceText:"请选择考试城市",
        areaStyle:"color: #B2B2B2;font-size:34rpx",
        certPlaceStyle:"color: #B2B2B2;font-size:34rpx",
        errorFocusName:"",
        num:0,
        isNoticeShow:false,
        isAdvertShow:false,
        advertIconUrl:"",
        needInvoice:0,
        agree:0,
        isShowFootNav:true,
        isCanScroll:true,
        list:[
            {
                "id": 440100,
                "name": "广州市"
            },
            {
                "id": 440200,
                "name": "韶关市"
            },
            {
                "id": 440300,
                "name": "深圳市"
            },
            {
                "id": 440400,
                "name": "珠海市"
            },
            {
                "id": 440500,
                "name": "汕头市"
            },
            {
                "id": 440600,
                "name": "佛山市"
            },
            {
                "id": 440700,
                "name": "江门市"
            },
            {
                "id": 440800,
                "name": "湛江市"
            },
            {
                "id": 440900,
                "name": "茂名市"
            },
            {
                "id": 441200,
                "name": "肇庆市"
            },
            {
                "id": 441300,
                "name": "惠州市"
            },
            {
                "id": 441400,
                "name": "梅州市"
            },
            {
                "id": 441500,
                "name": "汕尾市"
            },
            {
                "id": 441600,
                "name": "河源市"
            },
            {
                "id": 441700,
                "name": "阳江市"
            },
            {
                "id": 441800,
                "name": "清远市"
            },
            {
                "id": 441900,
                "name": "东莞市"
            },
            {
                "id": 442000,
                "name": "中山市"
            },
            {
                "id": 445100,
                "name": "潮州市"
            },
            {
                "id": 445200,
                "name": "揭阳市"
            },
            {
                "id": 445300,
                "name": "云浮市"
            }
        ]
    },
    onShareAppMessage: function () {   //分享功能
        return {
            title: '驾驶证邮寄服务',
            desc: '驾驶证邮寄服务',
            path: '/pages/handle/handle?scene='+app.globalData.channelId
        }
    },
    onLoad: function (options) {
        // options 中的 scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
        app.globalData.channelId = decodeURIComponent(options.scene)=='undefined'?'':decodeURIComponent(options.scene);
        console.log("channelId",app.globalData.channelId);
        var pageObj = this;

        var advertOpt = {   //请求广告
            url: app.globalData.host + "/wx/de/ad.ajax",
            data: {},
            sucFn: function (result) {
                if(result.body.icon) {
                    pageObj.setData({
                        isAdvertShow: true,
                        advertIconUrl: result.body.icon
                    });
                }
            }
        };
        app.ajax(advertOpt);



        app.initAddress();
        var page =  app.getStorageSync(app.globalData.cachePageKey);
        if(page!=null&&page!=""){
            this.setData({
                "cardNbr":page.cardNbr,
                "cardName":page.cardName,
                "certPlaceName":page.certPlaceName,
                "certPlaceProvinceId":page.certPlaceProvinceId,
                "certPlaceCityId":page.certPlaceCityId,
                "agree":page.agree
            });

            if(page.cardNbr!=''&&page.cardNbr!=null){
                if( FormCheckRule.idCardRule1.test(page.cardNbr)&& page.cardNbr.length == 15 ) {
                    this.setData({"cardNbrIconType": "success"});
                } else if (FormCheckRule.idCardRule2.test(page.cardNbr)&&page.cardNbr.length == 18) {
                    this.setData({"cardNbrIconType": "success"});
                } else if(page.cardNbr.length>0){
                    this.setData({"cardNbrIconType": "error"});
                }else{
                    this.setData({"cardNbrIconType": ""});
                }
            }

            if(page.cardName!=''&&page.cardName!=null) {
                if (FormCheckRule.nameRule.test(page.cardName)) {
                    this.setData({"cardNameIconType": "success"});
                } else if (page.cardName.length > 0) {
                    this.setData({"cardNameIconType": "error"});
                } else {
                    this.setData({"cardNameIconType": ""});
                }
            }


            if(page.address!=null){
                this.setData({
                    "area":page.area,
                    "areaStyle":"",
                    "address.street":page.address.street,
                    "address.provinceId":page.address.provinceId,
                    "address.cityId":page.address.cityId,
                    "address.countyId":page.address.countyId,
                    "address.provinceName":page.address.provinceName,
                    "address.cityName":page.address.cityName,
                    "address.countyName":page.address.countyName,
                    "address.cellNum":page.address.cellNum,
                    "address.contactName":page.address.contactName
                });
                if(page.address.contactName!=''&&page.address.contactName!=null) {
                    if (FormCheckRule.nameRule.test(page.address.contactName)) {
                        this.setData({"contactNameIconType": "success"});
                    } else if (page.address.contactName.length > 0) {
                        this.setData({"contactNameIconType": "error"});
                    } else {
                        this.setData({"contactNameIconType": ""});
                    }
                }

                if(page.address.cellNum!=''&&page.address.cellNum!=null) {
                    if (FormCheckRule.telRule.test(page.address.cellNum)) {
                        this.setData({"cellNumIconType": "success"});
                    } else if (page.address.cellNum.length > 0) {
                        this.setData({"cellNumIconType": "error"});
                    } else {
                        this.setData({"cellNumIconType": ""});
                    }
                }
                if(page.area=='请选择所在地区'){
                    this.setData({areaStyle: "color: #B2B2B2;font-size:34rpx"});
                }else{
                    this.setData({areaStyle: "color:#1a1a1a;font-size:34rpx"});
                }
                if(page.certPlaceName==''){
                    this.setData({certPlaceStyle: "color: #B2B2B2;font-size:34rpx"});
                }else{
                    this.setData({certPlaceStyle: "color:#1a1a1a;font-size:34rpx",certPlaceText:page.certPlaceName});
                }
            }
        }
    },
    onHide:function () {
        app.setStorageSync(app.globalData.cachePageKey,this.data);
    },
    onShow:function () {
        var pageObj = this;
        if(app.globalData.isAuthSuccess){
            pageObj.getUserOrderList();
        }else {
            wx.login({//调用登录接口
                success: function (res) {
                    var opt = {//后台兑换openId
                        url: app.globalData.host + "/wx/de/eo.ajax",
                        data: {
                            'code': res.code
                        },
                        sucFn: function (result) {
                            if(result.body.authSuccess){
                                app.globalData.openId = result.body.openId;
                                app.globalData.isAuthSuccess = result.body.authSuccess;
                                pageObj.getUserOrderList();
                            }else{
                                app.toastAuthFailModal();
                            }
                        }
                    };
                    app.ajax(opt);
                }
            });
        }
       var page = app.getStorageSync(app.globalData.cachePageKey);
        this.setData({
            num: page.num
        });
       if( page.cardNbr==null){
           this.setData({cardNbr:null,cardName:null,"cardNbrIconType": "",cardNameIconType:""});
       }
    },
    certPlaceTap:function () {
        var pageObj = this;
        setTimeout(function(){
            pageObj.setData({
                isCanScroll:false,
                showViewList: true,
                isShowFootNav: false
            });
        },100)
    },
    sureItemValueTap:function (e) {
        this.setData({
            isCanScroll:true,
            showViewList: false,
            certPlaceStyle: "",
            certPlaceText: "广东省"+e.target.dataset.name,
            certPlaceName: "广东省"+e.target.dataset.name,
            certPlaceCityId: e.target.dataset.code,
            isShowFootNav: true
        });
    },
    hideSelection: function(){
        this.setData({
            isCanScroll:true,
            showViewList: false,
            isShowFootNav: true
        });
    },

    //底部切换页面方法
    toUrl:function (e) {
     var url = e.currentTarget.dataset.url;
     if(url!='/pages/handle/handle'){
	     app.setStorageSync(app.globalData.cachePageKey,this.data);
	     if(url == ''){
		     //develop（开发版），trial（体验版），release（正式版）
		     var res = {
                 appid:app.globalData.appid,
                 path: app.globalData.path,
                 envVersion: app.globalData.envVersion
		     }
		     app.crossToUrl(res)
       }else {
         app.redirectTo({url: url+'?scene='+app.globalData.channelId});
       }
     }
    },

    infoInput:function (e) {
        var id = e.currentTarget.id;
        var value = e.detail.value.replace(/(^\s*)|(\s*$)/g,"");
        if(id=="cardNbr"){
            value = value.substr(0, 18);
            this.setData({"cardNbr": value});
            if( value =='') {
                this.setData({"cardNbrIconType": "success"});
            } else if( value.length == 15 && FormCheckRule.idCardRule1.test(value)) {
                this.setData({"cardNbrIconType": "success"});
            } else if (value.length == 18 && FormCheckRule.idCardRule2.test(value)) {
                this.setData({"cardNbrIconType": "success"});
            } else if(value.length>0){
                this.setData({"cardNbrIconType": "error"});
            }else{
                this.setData({"cardNbrIconType": ""});
            }

        }else if(id=="cardName"){
            this.setData({"cardName": value});
            if( value =='') {
                this.setData({"cardNameIconType": "success"});
            } else if(FormCheckRule.nameRule.test(value)) {
                this.setData({"cardNameIconType": "success"});
            } else if(value.length>0){
                this.setData({"cardNameIconType": "error"});
            }else{
                this.setData({"cardNameIconType": ""});
            }

        }else if(id=="address.contactName"){
            this.setData({"address.contactName": value});
            if( value =='') {
                this.setData({"contactNameIconType": "success"});
            } else if(value.length>0&&FormCheckRule.nameRule.test(value)) {
                this.setData({"contactNameIconType": "success"});
            } else if(value.length>0){
                this.setData({"contactNameIconType": "error"});
            }else{
                this.setData({"contactNameIconType": ""});
            }
        }else if(id=="address.cellNum"){
            value = value.substr(0, 11);
            this.setData({"address.cellNum": value});
            if( value =='') {
                this.setData({"cellNumIconType": "success"});
            } else if(FormCheckRule.telRule.test(value)) {
                this.setData({"cellNumIconType": "success"});
            } else if(value.length>0){
                this.setData({"cellNumIconType": "error"});
            }else{
                this.setData({"cellNumIconType": ""});
            }
        }else if(id=="address.street"){
            this.setData({"address.street": value});
            if( value =='') {
                this.setData({"streetIconType": "success"});
            } else if(value.length>=5) {
                this.setData({"streetIconType": "success"});
            }else if(value!=''&&value!=null&&value.length<5){
                this.setData({"streetIconType": "error"});
            }else{
                this.setData({"streetIconType": ""});
            }
        }
    },
    getUserOrderList:function () {
        var that = this;
        var opt2 = {
            url: app.globalData.host+"/wx/de/list.ajax",
            data: {
                'accountId':app.globalData.openId,
                'bizFlag':app.globalData.bizDoingFlag,
                'orderType':app.globalData.orderType
            },
            sucFn:function (result) {
                var num = "";
                if(result.body.orderList.length!=0){
                    num = result.body.orderList.length;
                }
                that.setData({
                    "num": num
                });
            }
        };
        app.ajax(opt2);
    },
    cardNbrBlur:function (e) {
        var value = e.detail.value;
        if(value!=null&&value!=''){
            this.setData({cardNbr: value.toUpperCase()});
        }
    },
    formSubmit:function (e) {
        var formData = e.detail.value;
        var cardNbr = formData.cardNbr;
        var cardName = formData.cardName;
        var certPlaceCityId = formData.certPlaceCityId;
        var cellNum = formData['address.cellNum'];
        var contactName = formData['address.contactName'];
        var street = formData['address.street'];
        var provinceId = formData['address.provinceId'];
        if(certPlaceCityId==''){
            this.setData({errorScrollIntoViewName: "handleView"});
            app.errorToast(FormCheckRule.certPlaceNameNullMessage);
            return false;
        }

        var flag = app.check([
            {
                value: cardName,
                errorFocusName:"cardName",
                errorScrollIntoViewName:"certPlaceNameView",
                fn: function (value) {
                    if(''==value){
                        app.errorToast(FormCheckRule.cardNameNullMessage);
                        return false;
                    }else if(FormCheckRule.nameRule.test(value)){
                        return true;
                    }else{
                        app.errorToast(FormCheckRule.cardNameErrorMessage);
                        return false;
                    }
                }
            },
            {
                value: cardNbr,
                errorFocusName:"cardNbr",
                errorScrollIntoViewName:"cardNameView",
                fn: function (value) {
                    if(''==value){
                        app.errorToast(FormCheckRule.cardNbrNullMessage);
                        return false;
                    }else if( value.length == 15 && FormCheckRule.idCardRule1.test(value)) {
                        return true;
                    } else if (value.length == 18 && FormCheckRule.idCardRule2.test(value)) {
                        return true;
                    } else{
                        app.errorToast(FormCheckRule.cardNbrErrorMessage);
                        return false;
                    }
                }
            },
            {
                value: contactName,
                errorFocusName:"contactName",
                errorScrollIntoViewName:"cardNbrView",
                fn: function (value) {
                    if(''==value){
                        app.errorToast(FormCheckRule.contactNameNullMessage);
                        return false;
                    }else if(FormCheckRule.nameRule.test(value)){
                        return true;
                    }else{
                        app.errorToast(FormCheckRule.contactNameErrorMessage);
                        return false;
                    }
                }
            },
            {
                value: cellNum,
                errorFocusName:"cellNum",
                errorScrollIntoViewName:"contactNameView",
                fn: function (value) {
                    if(''==value){
                        app.errorToast(FormCheckRule.cellNumErrorMessage);
                        return false;
                    }else if(FormCheckRule.telRule.test(value)){
                        return true;
                    }else{
                        app.errorToast(FormCheckRule.cellNumErrorMessage);
                        return false;
                    }
                }
            },
            {
                value: provinceId,
                errorFocusName:"provinceId",
                errorScrollIntoViewName:"cellNumView",
                rule: app.globalData.Rule.required,
                fn: function (value) {
                    if(value!=''){
                        return true;
                    }else{
                        app.errorToast(FormCheckRule.areaNameNullMessage);
                        return false
                    }
                }
            },
            {
                value: street,
                errorFocusName:"street",
                errorScrollIntoViewName:"areaView",
                rule: app.globalData.Rule.required,
                fn: function (value) {
                    if(value.length>=5){
                        return true;
                    }else{
                        app.errorToast(FormCheckRule.streetNullMessage);
                        return false
                    }
                }
            }
        ]);
        if (!flag) {
            return false;
        }
        if(this.data.agree==0){
            app.errorToast("请阅读并同意《驾驶证邮寄服务协议》!");
            return false;
        }
        if(!app.globalData.isAuthSuccess){
            app.toastAuthFailModal();
            return false;
        }
        var param = formData;
        param['address.fullAddr'] = formData['address.provinceName']+formData['address.cityName']+formData['address.countyName']+street;
        var opt = {
            url: app.globalData.host+"/wx/de/handling.ajax",
            data: param,
            sucFn:function (result) {
                param['serviceFee'] = result.body.serviceFee;
                param['serviceFeeDesc'] = result.body.serviceFeeDesc;
                param['totalChargeFee'] = result.body.totalChargeFee;
                param['totalFee'] = result.body.totalFee;
                app.setStorageSync(app.globalData.cacheOrderResKey, param);
                app.navigateTo({url:'../payment/payment'});
            }
        };
        app.ajax(opt);
    },
    //说明内容
    agreeTap:function (e) {
        app.navigateTo({url: '../notice/notice'});
    },
    checkTap:function (e) {
        var agree = e.target.dataset.agree;
        if(agree==0){
            agree = 1;
        }else{
            agree = 0;
        }
        this.setData({agree: agree});
    },
    noticeKnowTap:function (e) {
        this.setData({
            isNoticeShow:false,
            isShowFootNav:true
        });
    },
    areaTap:function (e) {
        this.setData({
            isAddressShow: true,
            isShowFootNav:false
        });
    },
    addressShowTap:function (e) {
        this.setData({
            isAddressShow: false,
            isShowFootNav:true
        });
    },
    bindAddressChange: function (e) {
        app.bindAddressChange(e);
    },
    confirmAddressTap:function (e) {
        var current_value = this.data.value;
        var provinceName = this.data.proviceData[current_value[0]].name;
        var cityName = this.data.cityData[current_value[1]].name;
        var countyName = "";
        if(this.data.districtData[current_value[2]].name!=null){
            countyName = this.data.districtData[current_value[2]].name;
        }
        this.setData({
            isShowFootNav:true,
            isAddressShow: false,
            areaStyle:"color:#1a1a1a;font-size:34rpx",
            area:provinceName+cityName+countyName,
            "address.provinceId":this.data.proviceData[current_value[0]].id,
            "address.cityId":this.data.cityData[current_value[1]].id,
            "address.countyId":this.data.districtData[current_value[2]].id,
            "address.provinceName":provinceName,
            "address.cityName":cityName,
            "address.countyName":countyName
        });
    },
    cancelAddressTap:function (e) {
        this.setData({
            isShowFootNav:true,
            isAddressShow: false
        });
    }
});
